# -*- coding: utf-8 -*-
from AdbUtils import ADB
import HtmlTemplate as HtmlTemplate
from ConfigUtil import ConfigIni
import SystemLogFilter as FilterLog
from FileUtils import all_file_path,get_sub_dir_files
import LogUtil as L
import yaml
import os

class GenerateReports:
    def __init__(self,all_result_path,device):
        self.all_result_path=all_result_path
        self.device=device
        self.adb=ADB(self.device)
        # self.image_name=image_name


    def make(self,show_statistic_image=False):
        """
        生成测试报告主函数
        根据status yaml的文件来生成测试报告
        :return:
        """
        # self.__filter_log()
        result=self.__yaml_file(self.all_result_path,'.yaml')
        lst=[]
        count_result=[] #记录测试用列结果
        for case_name,file_path in result.items():
            case_name=str(case_name).split('.')[0]
            case_result,cost_time=self.__open_yaml(file_path)
            count_result.append(case_result)
            # case_img=self.__check_file(str(file_path).replace('status', 'img').replace('yaml', 'jpg'))
            case_img =get_sub_dir_files(os.path.dirname(os.path.dirname(file_path)),"*.jpg")[0]
            case_per = self.__check_file(
                str(file_path).replace(
                    'status', 'per').replace(
                    'yaml', 'png'))
            case_log = self.__check_file(
                str(file_path).replace(
                    'status', 'log').replace(
                    'yaml', 'log').replace(case_name,  'steps'))
            case_filter = self.__check_file(
                str(file_path).replace(
                    'status', 'log').replace(
                    'yaml', 'log').replace(case_name,  'outPut'))
            if case_per is None:
                ini=ConfigIni()
                case_per=ini.get_ini('test_case','error_img')
            lst.append(
                HtmlTemplate.get_html_tr(
                    case_name,
                    case_result,
                    case_img,
                    case_per,
                    case_log,
                    case_filter,
                    cost_time
                )
            )
        HtmlTemplate.make_html(
            ''.join(lst),
            self.__app_info(),
            self.__device_info(),
            self.__test_case_execution_status(),
            count_result,
            self.all_result_path,
            show_statistic_image
        )
 
    def __filter_log(self):
        filter=FilterLog.FilterLog(self.all_result_path)
        filter.start()

    def __yaml_file(self, all_path_result, the_suffix_name):
        """
        :return: 错误报告列表
        """
        return all_file_path(all_path_result, the_suffix_name)

    def __open_yaml(self, file_path):
        '''
        获取status yaml文件内的值
        :param file_path:  status yaml文件路径
        :return:
        '''
        if file_path is None:
            return None
        with open(file_path) as f:
            y=yaml.load(f)
            return y['error_msg'],y["cost_time"]

    def __check_file(self, file_path):
        '''
        检查文件是否存在
        :param file_path:
        :return:
        '''
        if os.path.exists(file_path):
            return file_path
        else:
            return None

    @L.log()
    def __app_info(self):
        '''
        获取应用包名和版本号
        :return:
        '''
        # ini=ConfigIni()
        # packageName=ini.get_ini('test_package_name','package_name')
        packageName =self.adb.get_front_package_name()
        versionName=self.adb.get_app_version_name(packageName)
        return packageName,versionName
        pass

    @L.log()
    def __device_info(self):
        """
        用于生成测试报告的device的信息
        :return: 设备名,磁盘状态,wifi名称
        """
        return 'device_name:' + str(self.adb.get_device_name()), 'disk:' + str(self.adb.get_disk()), \
               'wifi_name:' + str(self.adb.wifi_name()), 'system_version:' + str(self.adb.get_android_version()), \
               'resolution:' + str(self.adb.get_screen_resolution())

    @L.log()
    def __test_case_execution_status(self):
        '''
        测试用例执行状态
        :return: 用例数，通过数，失败数
        '''
        number_of_test_case=self.__yaml_file(self.all_result_path[3],'.yaml').values()
        passed_the_test=0
        failed=0
        for i in number_of_test_case:
            result=self.__open_yaml(i)
            if isinstance(result,bool) and result:
                passed_the_test+=1
            else:
                failed+=1
        return len(number_of_test_case),passed_the_test,failed